﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Xml.Linq;
using stud.DTOs;

namespace stud.configurations
{
    public class PageConfig
    {

        public static PageInfo GetPageInfoByPageName(string pageName)
        {
            XElement pageConfig = GetPageConfig();
            return pageConfig.Elements("page")
                .Where(el => el.Attribute("name").Value.Equals(pageName))
                .Select(mn => new PageInfo
                                  {
                                      Name = mn.Attribute("name").Value,
                                      Url = mn.Attribute("url").Value,
                                      Roles = mn.Attribute("roles").Value.Split(',').ToList()
                                  }
                ).FirstOrDefault();
        }
        public static List<PageInfo> GetPageInfo()
        {
            XElement pageConfig = GetPageConfig();
            return pageConfig.Elements("page")
                .Select(mn => new PageInfo
                {
                    Name = mn.Attribute("name").Value,
                    Url = mn.Attribute("url").Value,
                    Roles = mn.Attribute("roles").Value.Split(',').ToList()
                }
                ).ToList();
        }


        private static XElement GetPageConfig()
        {
            XElement config = (XElement)HttpRuntime.Cache.Get("PageConfig");
            if (config == null)
            {
                string fileName = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, PageConfigPath);
                XDocument xDoc = XDocument.Load(fileName); // load the the xml file and get Documnet.
                config = xDoc.Element("pages");
                HttpRuntime.Cache.Add("PageConfig", config, new System.Web.Caching.CacheDependency(fileName), DateTime.Now.AddDays(7),
                        TimeSpan.Zero, System.Web.Caching.CacheItemPriority.High, null);
            }
            return config;
        }
        private static string PageConfigPath
        {
            get { return ConfigurationManager.AppSettings["PageConfigPath"]; }
        }
    }
}
